<?php

namespace app\model;

use app\model\UserOrder as ModelUserOrder;
use app\model\SysSetting as ModelSysSetting;

use think\Db;

class CourierInfo extends LoginCommon
{
    protected static $obj;

    public function _initialize()
    {
        parent::_initialize();
        $this->db_name = 'courier_info';
    }

    /**
     * 类入口
     * @return CourierInfo
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    /**
     * 快速注册
    */
    public function fastRegister($str_mobile)
    {
        $arr_data = [
            'mobile' => $str_mobile,
            'gmt_create' => $this->_now,
        ];
        return $this->toAdd($arr_data);
    }

    /*
     * 验证用户名字
     */
    public function checkCourierName($int_courier_id)
    {
        $field = 'real_name';
        return $this->toFind(['id'=>$int_courier_id],$field);
    }

    /**
     * 快递员信息
     */

    public function courierInfo($int_courier_id)
    {
        return $this->toFind(['id'=>$int_courier_id]);
    }

    /**
     * 获取快递员首页信息
     */
    public function getCourierInfo($arr_where,$int_first_row,$int_list_rows,$sort){
        $data = Db::name($this->db_name)
            ->where($arr_where)
            ->field('courier_info.id,courier_info.mobile,courier_info.real_name as name,courier_info.type,sum(case when courier_order.state =40 then 1 else 0 end) as closed,sum(case when courier_order.state =80 then 1 else 0 end) as send,courier_info.gmt_create as gmtCreate,courier_info.is_enable as isEnable')
            ->join('courier_order','courier_order.courier_id=courier_info.id','left')
            ->limit($int_first_row,$int_list_rows)
            ->group('courier_info.id')
            ->order("courier_info.gmt_create $sort")
            ->select();
        return $data;
    }

    /**
     * 获取快递员详情信息
     */
    public function getCourierDetail($arr_where){
        $detailData = Db::name($this->db_name)
            ->where($arr_where)
            ->field('id,gmt_create as gmtCreate,real_name as realName,sex,birthday,address,type,mobile,id_number as idNumber,start_term as startTerm,end_term as endTerm,idcard_front as idcardFront,idcard_back as idcardBack,head_portrait as headPortrait,delivery_address as deliveryAddress')
            ->select();
        //dump($detailData);die;
        $data = Db::name('express_certification')
            ->where("courier_id={$detailData[0]['id']}")
            ->field('expressId,express_branch AS expressBranch,job_number AS jobNumber,work_card AS workCard,address')
            ->find();
        //dump($data);die;
        if ($data){
            $expressName = Db::name('express')
                ->where("express_id={$data['expressId']}")
                ->value('express_name');
        }else{
            $expressName ='';
        }
        $detailData[0]['expressName']=$expressName;
        $detailData[0]['expressBranch']=$data['expressBranch'];
        $detailData[0]['jobNumber']=$data['jobNumber'];
        $detailData[0]['workCard']=$data['workCard'];
        $detailData[0]['distributionAddress']=$data['address'];
        return $detailData;
    }

    /**
     * 获取快递员统计信息
     */
    public function getCourierStatistical($arr_where){
        $withdrawal = Db::name($this->db_name)//提现总金额
            ->where($arr_where)
            ->field('ifnull(sum(withdraw_log.money),0) as withdrawal')
            ->join('withdraw_log','courier_info.id=map_id and withdraw_log.type=1')
            ->find();
        $loginNumber = Db::name($this->db_name)//登录次数
            ->where($arr_where)
            ->field('count(courier_info.id) as loginNumber')
            ->join('courier_passport','courier_passport.courier_id=courier_info.id')
            ->find();
        $cancelTheDelivery = Db::name($this->db_name)//取消投递记录
            ->where($arr_where)
            ->field('count(courier_order.courier_id) as cancelTheDelivery')
            ->join('courier_order','courier_info.id=courier_order.courier_id and courier_order.state=90')
            ->find();
        $send = Db::name($this->db_name)//派件总件数
            ->where($arr_where)
            ->field('count(courier_order.courier_id) as send')
            ->join('courier_order','courier_info.id=courier_order.courier_id and courier_order.state=80')
            ->find();
        $closed = Db::name($this->db_name)//寄件总件数
            ->where($arr_where)
            ->field('count(courier_order.courier_id) as closed')
            ->join('courier_order','courier_info.id=courier_order.courier_id and courier_order.state=40')
            ->find();
        $cancelOrder = Db::name($this->db_name)//取消订单记录
        ->where($arr_where)
            ->field('count(courier_order.courier_id) as cancelOrder')
            ->join('courier_order','courier_info.id=courier_order.courier_id and courier_order.state=0')
            ->find();
        $data=[
            'closed'            =>  $closed['closed'],
            'send'              =>  $send['send'],
            'cancelOrder'       =>  $cancelOrder['cancelOrder'],
            'cancelTheDelivery' =>  $cancelTheDelivery['cancelTheDelivery'],
            'withdrawal'        =>  $withdrawal['withdrawal'],
            'loginNumber'       =>  $loginNumber['loginNumber']
        ];
        return $data;
    }

    /**
     * 快递员资料编辑
     */
    public function getEditData($arr_where){
        $data = Db::name($this->db_name)
            ->where($arr_where)
            ->field('id,mobile,real_name as realName,id_number as idNumber,start_term as startTerm,end_term as endTerm,idcard_front as idcardFront,idcard_back as idcardBack,head_portrait as headPortrait,express,express_branch as expressBranch,job_number as jobNumber,work_card as workCard,address,is_enable as isEnable,delivery_address as deliveryAddress')
            ->select();
        return $data;
    }
    /*
     * 判断快递员是否已经入驻
     * 实名认证
     */
    public function checkIsAuth($courierId)
    {
        $info = $this->toFind(['id'=>$courierId],'state,auth_state as authState');
        if ($info['state'] !=1 || $info['authState'] !=1){
            return false;
        }
        return true;
    }

    /*
     * 返回快递员分佣
     */
    public function getCommission($mapId,$orderId){
        //获取订单信息
        $orderInfo = ModelUserOrder::getInstance()->toFind(['order_id'=>$orderId]);
        //获取快递员分佣类型
        $commissionType = $this->toValue(['id'=>$mapId],'commission_type');
        //添加快递员分佣
        if ($commissionType == 1){
            $commission = ModelSysSetting::getInstance()->courierCharges($commissionType);
        }elseif($commissionType == 2){
            $commission = ModelSysSetting::getInstance()->courierCharges($commissionType)*$orderInfo['order_amount']/100;
        }
        return $commission;
    }

}
